import { editPage } from '@/services/login';
import { formatImgItem, getImgUrl, jumpUrl } from '@/utils';
import { Button, Card, Collapse, Flex, Form, message } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import { useIntl, useModel } from 'umi';

import StepLive from '@/pages/Info/components/StepLive';
import StepOne from '@/pages/Info/components/StepOne';
import StepThree from '@/pages/Info/components/StepThree';
import StepTwo from '@/pages/Info/components/StepTwo';
import UploadList from '@/pages/Info/components/UploadList';

import arrow from '@/assets/center_arrow.png';
import userIcon from '@/assets/s_1.png';
import workIcon from '@/assets/s_2.png';
import moneyIcon from '@/assets/s_3.png';
import imgIcon from '@/assets/s_4.png';
//个人资料
const Data: React.FC = () => {
  const intl = useIntl();

  const { user, loading: userLoading, run } = useModel('userModel');
  const { setKey } = useModel('stepModel');
  const { setUploadParams, uploadParams } = useModel('uploadModel');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const genExtra = () => <></>;
  const items = useMemo(() => {
    return [
      {
        key: '1',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={userIcon} width={22} />
            <div> {intl.formatMessage({ id: 'home.user_info' })}</div>
          </Flex>
        ),
        children: (
          <div>
            <StepOne required={false} span={6} form={form} isCenter />
            <StepLive required={false} steps={2} span={6} form={form} isCenter />
          </div>
        ),
        extra: genExtra(),
        forceRender: true,
      },
      {
        key: '3',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={workIcon} width={22} />
            <div> {intl.formatMessage({ id: 'home.work_info' })}</div>
          </Flex>
        ),
        children: (
          <div>
            <StepTwo required={false} span={6} isCenter steps={2} form={form} />
          </div>
        ),
        extra: genExtra(),
        forceRender: true,
      },
      {
        key: '4',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={moneyIcon} width={28} style={{ marginLeft: -3 }} />
            <div> {intl.formatMessage({ id: 'home.user_prices' })}</div>
          </Flex>
        ),
        children: (
          <div>
            <StepThree required={false} span={6} isCenter form={form} />
            {/* {renderBtn('4')} */}
          </div>
        ),
        extra: genExtra(),
        forceRender: true,
      },
      {
        key: '5',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={imgIcon} width={22} />
            <div> {intl.formatMessage({ id: 'center.upload_data' })}</div>
          </Flex>
        ),
        children: <UploadList />,
        extra: genExtra(),
        forceRender: true,
      },
    ];
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [intl, form]);

  useEffect(() => {
    // 这里需要全量显示

    setKey([]);
    if (Object.keys(user || {}).length > 0 && !userLoading) {
      const {
        addressProof,
        bankMonthlyStatement,
        workProof,
        vehicleProof,
        estateProof,
        stockProof,
        cryptocurrencyProof,
        insuranceProof,
        otherProof,
        creditProof,
        birthday,
        graduationTime,
        userWorkInfo,
        loanInfo,
        idCardImg,
        idCardImg1,
        statementsConfirmFlag,
        ...rest
      } = user;

      if (!user.firstNameCn) {
        jumpUrl('/info');
      }
      const { ...val } = userWorkInfo || {};
      // 设置表单
      form.setFieldsValue({
        ...(birthday ? { birthday: dayjs(birthday) } : {}),
        // 入学时间
        ...(graduationTime ? { graduationTime: dayjs(graduationTime) } : {}),
        ...(loanInfo ? { loanInfo: JSON.parse(loanInfo) } : {}),
        ...rest,
        ...val,
      });
      // 设置全局上传的数据
      setUploadParams({
        idCard: {
          front: idCardImg,
          back: idCardImg1,
        },
        statementsConfirmFlag,
        bankMonthlyStatement: formatImgItem(bankMonthlyStatement),
        workProof: formatImgItem(workProof),
        vehicleProof: formatImgItem(vehicleProof),
        estateProof: formatImgItem(estateProof),
        stockProof: formatImgItem(stockProof),
        cryptocurrencyProof: formatImgItem(cryptocurrencyProof),
        otherProof: formatImgItem(otherProof),
        creditProof: formatImgItem(creditProof),
        addressProof: formatImgItem(addressProof),
        insuranceProof: insuranceProof
          ? JSON.parse(decodeURIComponent(encodeURIComponent(insuranceProof))).map((item: any) => {
              const { urls, ...rest } = item;
              return {
                ...rest,
                urls: formatImgItem(urls),
              };
            })
          : [],
      });
    }
  }, [user, form, intl, setUploadParams, setKey, userLoading, run]);
  return (
    <Form
      style={{ padding: '0', zIndex: 1, position: 'relative', background: 'none' }}
      className="info_right_form personCenter_form supplement_form personal_from"
      form={form}
      labelWrap={false}
      layout="vertical"
      requiredMark={false}
      onFinish={async (values) => {
        const { mobile, liabilitiesDetail, birthday, graduationTime, loanInfo, ...rest } = values;
        let uploadData: any = {};

        const {
          idCard: { back, front },
          addressProof,
          bankMonthlyStatement,
          estateProof,
          stockProof,
          vehicleProof,
          insuranceProof,
          cryptocurrencyProof,
          otherProof,
          creditProof,
          workProof,
          statementsConfirmFlag,
        } = uploadParams;
        uploadData = {
          idCardImg: front,
          idCardImg1: back,
          addressProof: getImgUrl(addressProof),
          // ...(bankMonthlyStatement.length > 0
          //   ? { bankMonthlyStatement: getImgUrl(bankMonthlyStatement) }
          //   : {}),
          bankMonthlyStatement: getImgUrl(bankMonthlyStatement),
          estateProof: getImgUrl(estateProof),
          stockProof: getImgUrl(stockProof),
          vehicleProof: getImgUrl(vehicleProof),
          insuranceProof:
            insuranceProof?.length > 0
              ? JSON.stringify(
                  insuranceProof.map((item: any) => {
                    const { urls, ...rest } = item as any;
                    return {
                      ...rest,
                      urls: getImgUrl(urls),
                    };
                  }),
                )
              : '',

          cryptocurrencyProof: getImgUrl(cryptocurrencyProof),
          otherProof: getImgUrl(otherProof),
          creditProof: getImgUrl(creditProof),
          workProof: getImgUrl(workProof),
          statementsConfirmFlag,
        };

        setLoading(true);
        try {
          const { code } = await editPage({
            ...uploadData,
            ...rest,
            ...(loanInfo ? { loanInfo: JSON.stringify(loanInfo) } : {}),
            ...(birthday ? { birthday: dayjs(birthday).format('YYYY-MM-DD') } : {}),
            ...(graduationTime
              ? { graduationTime: dayjs(graduationTime).format('YYYY-MM-DD') }
              : {}),
          });

          if (code === '100200') {
            message.success(intl.formatMessage({ id: 'center.suc_info' }));
            setLoading(false);
            // 更新数据
            run();
          }
        } catch {
          setLoading(false);
        }
      }}
    >
      <Card
        className="supplement_card"
        bordered={false}
        style={{ padding: '40px 32px', borderRadius: '0 0 8px 8px' }}
      >
        <div className="supplement_content">
          <Collapse
            expandIcon={(panelProps) => {
              const { isActive } = panelProps;
              return (
                <img
                  style={{ transition: 'all .5s', transform: `rotate(${isActive ? 180 : 0}deg)` }}
                  src={arrow}
                  width={25}
                />
              );
            }}
            expandIconPosition="end"
            bordered={false}
            items={items}
          />
        </div>
        <div style={{ marginTop: 24, textAlign: 'center' }}>
          <Button
            loading={loading}
            type="primary"
            style={{
              border: 'none',
              color: '#fff',
              padding: '0 84px',
              height: 60,
            }}
            htmlType="submit"
          >
            {intl.formatMessage({ id: 'home.save' })}
          </Button>
        </div>
      </Card>
    </Form>
  );
};

export default Data;
